package com.skyline.manage.feed;

import java.util.Date;
import java.util.Timer;

import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;

import com.skyline.manage.feed.task.FeedManageTask;

/**
 * FeedManager，Feed系统的后台管理程序
 * 
 * @author jairus
 * 
 */
public class FeedManager {

	/**
	 * 日志
	 */
	private static Logger logger = null;

	/**
	 * 日志初始化文件的路径
	 */
	private static String loggerInitialFilePath = null;

	/**
	 * ConfigLoader初始化文件的路径
	 */
	private static String configLoaderInitialFilePath = null;

	private static FeedManageTask task = null;

	private static Date firstTime = null;

	private static Long period = null;

	/**
	 * 初始化整个系统
	 * 
	 * @throws Exception
	 */
	private static void intialSystem(String[] args) throws Exception {

		if (args.length == 2) {
			loggerInitialFilePath = args[0];
			configLoaderInitialFilePath = args[1];
		} else {
			loggerInitialFilePath = FeedManager.class.getClassLoader().getResource("//").getPath() + "config/log4j.properties";
			configLoaderInitialFilePath = FeedManager.class.getClassLoader().getResource("//").getPath() + "config/feed.properties";
		}

		PropertyConfigurator.configure(loggerInitialFilePath);
		logger = Logger.getLogger(FeedManager.class);

		ConfigLoader.initial(configLoaderInitialFilePath);

		FeedCollections.initial();
		FeedCollections.open();

		String lifes = ConfigLoader.getValue("feed.task.life");
		task = new FeedManageTask(FeedCollections.getPersonalFeedCollections(), lifes, FeedCollections.getSubscribedFeedCollections());

		String[] firstTimeStrs = ConfigLoader.getValue("feed.task.firstTime").split(":");
		firstTime = new Date();
		Date firstTimeTmp = (Date) firstTime.clone();
		firstTimeTmp.setHours(Integer.valueOf(firstTimeStrs[0]));
		firstTimeTmp.setMinutes(Integer.valueOf(firstTimeStrs[1]));
		firstTimeTmp.setSeconds(Integer.valueOf(firstTimeStrs[2]));
		if (firstTime.getTime() >= firstTimeTmp.getTime()) {
			firstTimeTmp.setDate(firstTimeTmp.getDate() + 1);
		}
		firstTime = firstTimeTmp;
		period = Long.valueOf(ConfigLoader.getValue("feed.task.period")) * 3600 * 100;

	}

	/**
	 * main，入口
	 * 
	 * @param args
	 */
	public static void main(String[] args) {
		try {
			intialSystem(args);
			Timer timer = new Timer();
			timer.schedule(task, firstTime, period);

		} catch (Exception e) {
			logger.fatal("程序已经崩溃", e);
			// TODO:发送邮件，通知管理员
		}
	}

}
